"""
题目：https://leetcode-cn.com/problems/binary-tree-postorder-traversal/
    给定一个二叉树，返回它的 后序 遍历。
    示例:
    输入: [1,null,2,3]  
    1
        \
        2
        /
    3 
    输出: [3,2,1]
思路：迭代算法。
时间复杂度:O(n)
空间复杂度:O(n)

"""

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        stack = []
        res = []
        cur = root
        prev = None
        while stack or cur:
            while cur:
                stack.append(cur)
                cur = cur.left
            cur = stack.pop()
            if not cur.right or cur.right == prev:
                res.append(cur.val)
                prev = cur
                cur = None
            else:
                stack.append(cur)
                cur = cur.right
        return res
